// 封装统一的接口请求函数，返回数据格式使用ref
import type { UnwrapRef } from 'vue'
import { ref } from 'vue'
//UnwrapRef 是类型，里面的UnwrapRefSimaple是函数，用于解析获取原始值数据
export function useBaseAsync<T>(asyncFn: () => Promise<T>, initValue: T, immediate = true) {
  const pending = ref(false)
  const data = ref(initValue)
  const error = ref(null)

  const execute = function () {
    pending.value = true
    error.value = null
    return asyncFn()
      .then((res) => {
        data.value = res as UnwrapRef<T> //类型转换，映射
        pending.value = false
      })
      .catch((err) => {
        error.value = err
        pending.value = false
      })
  }

  if (immediate) {
    execute()
  }
  return {
    pending,
    data,
    error,
    execute
  }
}
